<template>
  <el-row :gutter="20" class="header">
    <el-col :span="7">
      <!-- 搜索输入框 -->
      <el-input placeholder="请输入用户名..." v-model="queryForm.query" clearable></el-input>
    </el-col>
    <!-- 搜索按钮 -->
    <el-button type="success" :icon="DocumentAdd" @click="AddUser">新增</el-button>
    <el-popconfirm title="您确定批量删除这些记录吗？" @confirm="handleDelete(null)">
      <template #reference>
        <el-button type="danger" :disabled="delBtnStatus" :icon="Delete">批量删除</el-button>
      </template>
    </el-popconfirm>
  </el-row>
  <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
     <el-table-column type="selection" width="55" :selectable="selectable"/>
    <el-table-column type="index" :index="indexMethod+((queryForm.pageNum-1)*queryForm.pageSize)" label="序号" width="100" align="center" />
    <!-- <el-table-column prop="id" label="用户id" width="180" /> -->
    <el-table-column prop="head" label="头像" width="80" align="center">
      <template v-slot="scope">
        <img :src="api.getServerUrl()+'media/defaultHead/'+scope.row.head" width="50" height="50" />
      </template>
    </el-table-column>
    <el-table-column prop="username" width="150" label="用户名" align="center" />
    <!-- <el-table-column prop="password" wlabel="密码" /> -->
    <el-table-column prop="email" width="200" label="邮箱" align="center" />
        <el-table-column prop="status" label="状态" align="center">
      <template v-slot="{row}">
          <el-tooltip :content="'状态: ' + (row.status === 0? '启用' : '禁用')" placement="top">
            <el-switch
                v-model="row.status"
                @change="statusChangeHandle(row)"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                :active-value="0"
                :inactive-value="1"
                v-if="row.role === '超级管理员'"
                disabled
            />
            <el-switch
                v-model="row.status"
                @change="statusChangeHandle(row)"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                :active-value="0"
                :inactive-value="1"
            />
          </el-tooltip>
        </template>
    </el-table-column>
    <el-table-column prop="balance" label="余额" align="center" width="100" >
      <template v-slot="{row}">
        {{ row.balance }}元
      </template>
    </el-table-column>
    <!-- <el-table-column prop="role" label="拥有角色" /> -->
    <el-table-column prop="create_time" label="创建时间" width="200" align="center" />
    <el-table-column prop="update_time" label="最近登录时间" width="200" align="center" />
    <el-table-column fixed="right" label="操作" min-width="200" align="center">
      <template #default="scope">
        <el-button link type="primary" v-show="scope.row.role !== '超级管理员'" size="small" @click="Edit(scope.row)">编辑</el-button>
          <el-popconfirm title="您确定重置这条记录吗？" @confirm="resetPassword(scope.row.id)">
            <template #reference>
            <el-button link type="primary" v-show="scope.row.role !== '超级管理员'" size="small">重置密码</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="您确定删除这条记录吗？" @confirm="handleDelete(scope.row.id)">
            <template #reference>
            <el-button link type="primary" v-show="scope.row.role !== '超级管理员'" size="small">删除</el-button>
            </template>
          </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    v-model:currentPage="queryForm.pageNum"
    v-model:page-size="queryForm.pageSize"
    :page-sizes="[10, 20, 30, 40]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  <el-dialog v-model="formVisible">
    <ResetForm v-if="formVisible" @cancel="formVisible = false" @submit="handleSubmit" :formData="formData" :userId="userId"></ResetForm>
  </el-dialog>
  <el-dialog v-model="formVisible2">
    <AddForm v-if="formVisible2" @cancel="formVisible = false" @submit="handleSubmit"></AddForm>
  </el-dialog>
</template>

<script setup>
import { ElTable } from "element-plus";
import { ref, onMounted ,watch} from "vue";
import ResetForm from "@/views/system/user/components/ResetForm.vue";
import AddForm from "@/views/system/user/components/AddForm.vue";
import requestUtil, { api } from "@/api/request.js";
import { debounce } from "lodash";
import { ElMessage } from "element-plus";
let userId = ref(0);
// 初始化序号值
let indexMethod = ref(1);
const selectable = (row)=>{
  return row.role !== '超级管理员';
}
// 初始化多选状态
let selections = ref([]);
const delBtnStatus = ref(true)
const handleSelectionChange = (selection) => {
  // 更新存储选中项的数组
  selections.value = selection
  // 更新批量删除按钮的状态
  delBtnStatus.value = selection.length <= 0
}
const queryForm = ref({
  query: "",
  pageNum: 1,
  pageSize: 10
});
// 创建一个防抖的搜索函数
const debouncedGetUserInfo = debounce(() => {
  getUserInfo();
}, 300);

// 使用防抖搜索函数
watch(() => queryForm.value.query, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    debouncedGetUserInfo();
  }
});
let tableData = ref([]);
let formVisible = ref(false);
let formVisible2 = ref(false);
let formData = ref();
let total = ref(0);
const statusChangeHandle = async (row) => {
  // 向服务器发送⽤户状态变更请求
  let res = await requestUtil.post("management/updateUserStatus/", {
    id: row.id, status: row.status
  });
  // 根据服务器返回的结果进⾏相应处理
  if (res.data.code == 200) {
    // 如果请求成功，显示成功消息
    ElMessage({
      type: 'success',
      message: '执⾏成功!'
    })
  } else {
    // 如果请求失败，显示错误消息，并重新初始化⽤户列表
    ElMessage({
      type: 'error',
      message: res.data.msg,
    })
    await getUserInfo();
  }
}
const getUserInfo = async () => {
  let res = await requestUtil.post("management/getUserInfo/", {
    query: queryForm.value.query,
    pageNum: queryForm.value.pageNum,
    pageSize: queryForm.value.pageSize
  });
  console.log(res);
  tableData.value = res.data.userInfo;
  total.value = res.data.total;
};
onMounted(() => {
  getUserInfo();
});
// 处理每页条数变化
const handleSizeChange = pageSize => {
  queryForm.value.pageNum = 1;
  queryForm.value.pageSize = pageSize;
  getUserInfo();
};
// 处理当前页变化
const handleCurrentChange = pageNum => {
  queryForm.value.pageNum = pageNum;
  getUserInfo();
};

const Edit = row => {
  userId.value = row.id;
  console.log(formData.value);
  getUserInfo();
  formVisible.value = true;
};
const AddUser = () => {
  formVisible2.value = true;
}
const handleSubmit = () => {
  getUserInfo();
  formVisible.value = false;
  formVisible2.value = false;
};
const handleDelete=async (id)=>{
  if(id){
    let res = await api.del(`management/deleteUser/?userId=${id}`)
    if(res.data.code === 200){
      await getUserInfo()
      ElMessage.success("删除成功")
    }
  }else{
    let ids = selections.value.map(item => item.id)
    if(ids.length === 0){
      ElMessage.error("请选择要删除的记录")
      return
    }
    else{
      let res = await api.del(`management/deleteUsers/?userIds=${[ids]}`)
      if(res.data.code === 200){
        await getUserInfo()
        ElMessage.success("删除成功")
      }
    }
  }
}
const resetPassword = async (id) => {
  let res = await requestUtil.put("management/resetPassword/",{userId:id})
  if(res.data.code === 200){
    ElMessage.success("重置密码成功")
  }
}
</script>